package nio.groupChat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;

/**
 * description:
 * author:zt
 * date:2021-09-17
 */
public class Client {

    private final String HOST = "127.0.0.1";  //服务器ip
    private final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    private String username;

    public Client() throws IOException {
        selector = Selector.open();
        //连接服务器
        socketChannel = SocketChannel.open();
        socketChannel.connect(new InetSocketAddress(HOST,PORT));
        socketChannel.configureBlocking(false);
        socketChannel.register(selector,SelectionKey.OP_READ);

        username = socketChannel.getLocalAddress().toString();
        System.out.println(username + "：is ok...");
    }

    public void sendInfo(String info){
        info = username + "说：" + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        }catch (IOException e){
            e.printStackTrace();
        }
    }

    public void readInfo(){
        try{
            int select = selector.select();
            if (select >0) { //有可用的通道
                Iterator<SelectionKey> iterator = selector.selectedKeys().iterator();
                while (iterator.hasNext()){
                    SelectionKey key = iterator.next();
                    if (key.isReadable()){
                        SocketChannel sc = (SocketChannel) key.channel();
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        sc.read(buffer); //读取
                        String msg = new String(buffer.array());
                        System.out.println(msg.trim());
                        iterator.remove();
                    }
                }
            }else {
//                System.out.println("无可用的通道...");
            }
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws IOException {
        Client client = new Client();
        //启动一个线程每隔三秒读取从服务器发送的数据
        new Thread() {
            public void run(){
                while (true){
                    client.readInfo();
                    try{
                        Thread.currentThread().sleep(3000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }.start();

        Scanner scanner = new Scanner(System.in);
        while (scanner.hasNextLine()){
            String s = scanner.nextLine();
            client.sendInfo(s);
        }
    }
}
